#define _CRT_SECURE_NO_WARNINGS 1

#include "mergesort.h"

void _mergesort(int* a, int begin, int end, int* tmp)
{

	if (begin >= end)
	{
		return;
	}
	int mid = (begin + end) / 2;

	//[begin,mid][mid+1,end]
	_mergesort(a, begin, mid, tmp);
	_mergesort(a, mid+1, end, tmp);

	int begin1 = begin, end1 = mid;
	int begin2 = mid + 1, end2 = end;
	int i = begin;
	while (begin1 <= end1 && begin2 <= end2)
	{
		if (a[begin1] < a[begin2])
		{
			tmp[i++] = a[begin1++];
		}
		else
		{
			tmp[i++] = a[begin2++];
		}
	}

	while (begin1 <= end1)
	{
		tmp[i++] = a[begin1++];
	}
	while (begin2 <= end2)
	{
		tmp[i++] = a[begin2++];
	}

	memcpy(a+begin,tmp+begin,((end-begin)+1)*sizeof(int));

}


void mergesort(int* a, int n)
{
	int* tmp = (int*)malloc(sizeof(int) * n);
	if(tmp == NULL)
	{
		perror("malloc");
		return;
	}

	_mergesort(a, 0, n - 1, tmp);

	free(tmp);
	tmp = NULL;
}
